/**
 * 聚合搜索模块
 * 先需要引入search.css
 */
("use strict");
(function () {
  const SEAR_MAP = {};
  layui.binder.extend({
    name: "search",
    data: function (dataSource) {
      let index = 1;
      let res = [
        {
          id: index++,
          mark: "全部",
          entry: "",
          querys: [],
          selectQuery: [],
        },
      ];
      _lodash.each(MAP, (value, key) => {
        res.push({
          id: index++,
          mark: value.mark,
          entry: key,
          querys: [],
          selectQuery: [],
        });
        SEAR_MAP[key] = value;
      });
      return { list: res };
    },
    /**
     * checkflag 防止点击切换标签页触发关闭事件
     * showflag  显示or隐藏搜索区域
     * pointer   当前聚合搜索的分组(key)
     * group     当前选中查看详情的分组(key)
     * searchText 当前的搜索值
     */
    template: `
    <div class="layui-windows-search-dashboard" *checkflag = "false"  *showflag = "false" *pointer *group *searchText :class = "layui-windows-search-{{showflag}}">
      <div class="layui-tab" lay-filter="layui-search-page">
        <ul class="layui-tab-title" v-each = "list" mark = "index" key = "id">
          <li :class = "index.id == 1 ? 'layui-this' : ''" :lay-id = "index.id">{{index.mark}}
            <div class = "layui-windows-search-titleBar"></div>
          </li>
        </ul>
        <div class="layui-tab-content" v-each = "list" mark = "index" key = "id" >
          <div :id = "layui-windows-search-{{index.id}}" class="layui-tab-item" :class = "index.id == 1 ? 'layui-show' : ''">
            <div class = "layui-search-list-bar" v-each = "index.querys" mark = "query" >
              <div class = "layui-search-list-nav" @click = "b.group = query.type" >
                <div class = "layui-search-list-title">{{query.mark}}</div>
                <div class = "layui-search-parts" v-each = "query.list" mark = "part">
                  <div class = "layui-search-part">{{part.elasticsearchHintcontent}}</div>
                </div>
              </div>
            </div>
            <div class = "layui-search-detail-bar layui-windows-desk-scroll" v-each = "index.selectQuery" mark = "query">
              <div class = "layui-search-detail-parts" v-each = "query.list" mark = "part">
                <div class = "layui-search-detail-part" v-each = "part.template" mark = "template">
                  <div>
                    <div class = "layui-search-detail-left">{{template.name}}</div>
                    <div class = "layui-search-detail-right">{{template.value}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>`,
    methods: {
      init() {
        // 初始化参数
        _lodash.each(this.list, (v) => {
          v.querys = [];
          v.selectQuery = [{ list: [] }];
        });
      },
      start() {
        if (this.checkflag !== "false") return;
        this.showflag = "true";
        // 参数归0
        this.searchText = "";
        // 回到第一列,触发查询
        if (!this.pointer) this.search();
        layui.element.tabChange("layui-search-page", 1);
      },
      stop() {
        // 隐藏dom
        if (this.checkflag == "false") {
          this.showflag = "false";
          return true;
        } else {
          return false;
        }
      },
      search() {
        let self = this;
        self.init();
        let pointer = this.pointer || "";
        let searchText = this.searchText || "";
        $.ajax({
          url: LAYER_BASE_URL + "/index/search",
          type: "POST",
          dataType: "json",
          contentType: "application/json",
          data: JSON.stringify({ name: searchText, type: pointer }),
          success: function (res) {
            if (res.code == 200) var map = self.feature(res.data, 6);
            var list = [];
            _lodash.each(map, (v) => {
              if (v.list && v.list.length > 0) list.push(v);
            });
            /**
             * 筛选第一个分组作为当前查看的分组
             */
            _lodash.each(self.list, (value) => {
              if (value.entry == pointer) {
                value.querys = list;
                if (list.length > 0) {
                  if (self.group == list[0].type) {
                    // 值如果没有变化就手动触发一次
                    self.changeGroup();
                  } else {
                    self.group = list[0].type;
                  }
                }
              }
            });
            // setTimeout(function(){
            $(".layui-search-part").each(function () {
              var html = $(this).text();
              $(this).html(layui.transformElasticsearchHint(html));
            });
            // },500);
          },
        });
      },
      /**
       * 抽取数据
       */
      feature(input, total, count = 0, wheel = 0, output = {}) {
        _lodash.each(input, (list, type) => {
          if (!output[type])
            output[type] = {
              type: type,
              mark: SEAR_MAP[type].mark,
              list: [],
            };
          if (count < total && list[wheel]) {
            count++;
            // 如果没有高亮信息，就使用对应的参数生成一个展示的信息
            if (!list[wheel].elasticsearchHintcontent)
              list[wheel].elasticsearchHintcontent = SEAR_MAP[type].title(
                list[wheel]
              );
            output[type].list.push(list[wheel]);
          }
        });
        if (count >= total || wheel > total) return output;
        return this.feature(input, total, count, ++wheel, output);
      },
      /**
       * 外界调用，更新搜索值
       * @param {*} value 
       */
      change(value) {
        this.searchText = value;
      },
      /**
       * 切换当前展示的分组详细信息
       */
      changeGroup() {
        let self = this;
        _lodash.each(self.list, (value) => {
          if (value.entry == self.pointer) {
            if (value.querys.length > 0) {
              _lodash.each(value.querys, (query) => {
                if (query.type == self.group) {
                  let selectList = [];
                  let fn = SEAR_MAP[query.type].parse;
                  _lodash.each(query.list, (v) => {
                    selectList.push({
                      template: fn(v),
                    });
                  });
                  value.selectQuery[0].list = selectList;
                }
              });
            }
          }
        });
      },
    },
    mounted() {
      let self = this;
      /**
       * 选项卡切换事件，修改当前用于搜索的分组，进行搜索
       */
      layui.element.on("tab(layui-search-page)", function (data) {
        self.searchVisable = "true";
        self.pointer = self.list[data.index].entry;
      });
      /**
       * 当前用于搜索的分组改变时，进行搜索
       */
      self.$watch("pointer", {
        immediate: false,
        deep: false,
        handler() {
          self.search();
        },
      });
      /**
       * 当前的搜索值改变时，进行搜索
       */
      self.$watch("searchText", {
        immediate: false,
        deep: false,
        handler() {
          self.search();
        },
      });
      self.$watch("group", {
        immediate: false,
        deep: false,
        handler() {
          self.changeGroup();
        },
      });
      /**
       * 搜索主提位置点击时不要关闭搜索块
       */
      $(self.parent).on("click", ".layui-tab-content", function (e) {
        e.stopPropagation();
        e.preventDefault();
        self.searchVisable = "true";
      });
      /**
       * 点选项卡是阻止默认的关闭行为
       */
      $(self.parent).on("mouseup", ".layui-tab-title", function (e) {
        self.checkflag = "true";
        setTimeout(function () {
          self.checkflag = "false";
        }, 500);
      });
      /**
       * 点击标题菜单时滚动到对应的位置
       */
      $(self.parent).on("click", ".layui-search-part", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var index = $(this).parent().find(".layui-search-part").index(this);
        var parentNode = $(".layui-show .layui-search-detail-bar.layui-windows-desk-scroll");
        var othis = $(".layui-show .layui-search-detail-parts")
          .find(".layui-search-detail-part")
          .eq(index);
        parentNode.animate(
          {
            scrollTop:
              othis.offset().top -
              parentNode.offset().top +
              parentNode.scrollTop(),
          },
          300
        );
      });
    },
  });
  var VM;
  const SEARCH_ID = "layui-search";
  layui.enableSearch = function (crc) {
    if (crc) CRC = crc;
    if (VM) return VM;
    $("body").append(
      $(`
      <div id = "${SEARCH_ID}">
        <search></search>
      </div>
    `)
    );
    VM = layui.binder({
      el: "#" + SEARCH_ID,
      components: {
        search: "search",
      },
      beforeDestroy() {
        $body.find("#" + SEARCH_ID).remove();
      },
    });
    return VM;
  };
})();
